/* eslint-disable no-param-reassign */
import { message } from 'antd';
import {
  templateList,
  delTemplateList,
  delInforList,
  delMatList,
  getPdList,
  getMatDetail,
  getAreaInsUnify,
  getDictAss,
  getCorpDict,
  save,
  update,
} from '@/services/material';
import router from 'umi/router';
import { getJudgeDict, getMatListPage, getDict, getAreaList } from '@/services/inservicematerial';
import changeName from '../InserviceMaterial/changeTxt';

export default {
  state: {
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    },
    tabList: [
      { itemCode: '1', itemName: '邮件/短信模板' },
      { itemCode: '2', itemName: '入职告知' },
      { itemCode: '3', itemName: '入职材料' },
    ],
    areaList: [],
    activeKey: '1',
    formFieldsValue: {},
    pdListData: [],
    // 材料 新增 修改
    titleArr: [true],
    headertitle: ['标题'],
    tValue: [[]],
    newNo: 0,
    tableArr: [{ pageIdEdit: 0, maGpDetails: [] }],
    requestData: [],
    addMetial: [],
    tableJudge: [],
    logicList: [],
    tValues: '',
    tValueCode: '',
    index: 0,
    bigResult: [],
    logicArr: [],
    coltFlag: '1',
  },

  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put, select }) {
      const activeKey = yield select(state => state.material.activeKey);
      if (Number(activeKey) !== 1) {
        const newPayload = payload;
        newPayload.page = payload.pagerArg;
      }
      const response = yield call(templateList, payload, activeKey);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.error(response.message || '服务端错误');
      }
    },
    // 获取地区
    *fetchAreaList({ payload }, { call, put }) {
      const response = yield call(getAreaList, payload);
      if (response.success) {
        yield put({
          type: 'getAreaList',
          payload: response.data,
        });
      }
    },
    // 删除模板
    *delTemplate({ payload }, { call, put, select }) {
      const response = yield call(delTemplateList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.material.data.pagination.current;
          const { pageSize } = state.material.data.pagination;
          const { formFieldsValue } = state.material;
          const pagerArg = { currentPage, pageSize };
          values = {
            pagerArg,
            ...formFieldsValue,
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 删除入职告知
    *delInfor({ payload }, { call, put, select }) {
      const response = yield call(delInforList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.material.data.pagination.current;
          const { pageSize } = state.material.data.pagination;
          const { formFieldsValue } = state.material;
          const pagerArg = { currentPage, pageSize };
          values = {
            pagerArg,
            entryInformVo: { ...formFieldsValue },
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 删除材料
    *delMat({ payload }, { call, put, select }) {
      const response = yield call(delMatList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.material.data.pagination.current;
          const { pageSize } = state.material.data.pagination;
          const { formFieldsValue } = state.material;
          const pagerArg = { currentPage, pageSize };
          values = {
            pagerArg,
            mat: { ...formFieldsValue },
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 获取产品
    *fetchPdList({ payload }, { call, put }) {
      const response = yield call(getPdList, payload); // 请求
      if (response.success) {
        yield put({
          type: 'getPdList',
          payload: response.data,
        });
      }
    },
    // 获取判断
    *fetchJudgeDict({ payload }, { call, put }) {
      const response = yield call(getJudgeDict, payload);
      if (response.success) {
        yield put({
          type: 'getJudgeDict',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
      return response;
    },
    // 获取材料
    *fetchMatListPage({ payload }, { call, put }) {
      const response = yield call(getMatListPage, payload);
      if (response.success) {
        yield put({
          type: 'getMatListPage',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    *fetchDict({ payload }, { call, put, select }) {
      const response = yield call(getDict, payload);
      const matPkgId = yield select(state => state.routing.location.query.id);
      if (response.success) {
        yield put({
          type: 'getDict',
          payload: response.data,
        });
        // 地区
        const resArea = yield call(getAreaList, {});
        if (resArea.success) {
          yield put({
            type: 'getAreaList',
            payload: resArea.data,
          });
        } else {
          message.warning(resArea.message || '服务端错误');
        }
        // 详情
        if (matPkgId) {
          const res = yield call(getMatDetail, { matPkgId });
          if (res.success) {
            // 根据地区再查一遍
            const resAreaIns = yield call(getAreaInsUnify, { areaId: res.data.areaId });
            if (resAreaIns.success) {
              yield put({
                type: 'getAreaInsUnify',
                payload: resAreaIns.data,
              });

              if (Number(resAreaIns.data.insUnifyFlag) === 2) {
                const resDictAss = yield call(getDictAss, ['BIZ_INS_TYPE']);
                if (resDictAss.success) {
                  yield put({
                    type: 'getDictAss',
                    payload: resDictAss.data,
                  });
                } else {
                  message.warning(resDictAss.message || '服务端错误');
                }
              }
              // 详情
              yield put({
                type: 'getMatDetail',
                payload: res.data,
              });
            } else {
              message.warning(resAreaIns.message || '服务端错误');
            }
          } else {
            message.warning(res.message || '服务端错误');
          }
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 获取产品
    *fetchAreaInsUnify({ payload }, { call, put }) {
      const response = yield call(getAreaInsUnify, payload);
      if (response.success) {
        yield put({
          type: 'getAreaInsUnify',
          payload: response.data,
        });

        if (Number(response.data.insUnifyFlag) === 2) {
          const res = yield call(getDictAss, ['BIZ_INS_TYPE']);
          if (res.success) {
            yield put({
              type: 'getDictAss',
              payload: res.data,
            });
          } else {
            message.warning(res.message || '服务端错误');
          }
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
    // 不同条件显示不同逻辑条件
    *fetchCorpDict({ payload }, { call, put }) {
      const response = yield call(getCorpDict, payload);
      if (response.success) {
        yield put({
          type: 'getJudgeDict',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务端错误');
      }
      return response;
    },
    *fetchSave({ payload }, { call, select }) {
      const matPkgId = yield select(state => state.material.matPkgId);
      const vno = yield select(state => state.material.vno);
      const response = matPkgId
        ? yield call(update, { ...payload, matPkgId, vno })
        : yield call(save, payload);
      if (response.success) {
        if (response.data) {
          message.warning('温馨提示：您配置的地区与材料类型已存在');
        } else {
          router.goBack();
        }
      } else {
        message.warning(response.message || '服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取地区
    getAreaList(state, { payload }) {
      return {
        ...state,
        areaList: payload,
      };
    },
    // 获取材料
    getMatListPage(state, { payload }) {
      return {
        ...state,
        requestData: payload.pageRecords,
        addMetial: JSON.parse(JSON.stringify(payload.pageRecords)),
        tableJudge: JSON.parse(JSON.stringify(payload.pageRecords)),
        cmTotal: payload.totalCount,
      };
    },
    // 获取判断
    getJudgeDict(state, { payload }) {
      return {
        ...state,
        logicList: payload,
      };
    },
    getPdList(state, { payload }) {
      return {
        ...state,
        pdListData: JSON.parse(JSON.stringify(payload)),
        pdList: JSON.parse(JSON.stringify(payload)), //
      };
    },
    // 获取字典
    getDict(state, { payload }) {
      return {
        ...state,
        flagList: payload.YES_NO_FLAG,
        inputType: payload.INPUT_TYPE,
        contractlist: payload.SER_TYPE, // 合同类型
      };
    },
    // 新增 修改
    addTable(state) {
      const newState = state;
      newState.tableArr.push({ pageIdEdit: (newState.index += 1), maGpDetails: [] });
      newState.titleArr.push(true);
      newState.headertitle.push('标题');
      newState.tValue.push([]);
      return {
        ...state,
      };
    },
    modifyTitle(state, { payload }) {
      state.titleArr.splice(payload, 1, false);
      return {
        ...state,
      };
    },
    saveTitle(state, { payload }) {
      state.titleArr.splice(payload, 1, true);
      return {
        ...state,
      };
    },
    changeTitle(state, { payload }) {
      state.headertitle.splice(payload.i, 1, payload.v);
      return {
        ...state,
      };
    },
    updateTable(state, { payload }) {
      const newPayload = payload;
      state.tableArr[state.newNo].maGpDetails.push(newPayload);
      state.tValue[state.newNo].push([]);
      if (Number(newPayload.judgeFlag) === 1) {
        newPayload.children = [];
      }
      return {
        ...state,
        tableArr: JSON.parse(JSON.stringify(state.tableArr)),
      };
    },
    updateTableChild(state, { payload }) {
      const newPayload = payload;
      newPayload.selectedRows.judgeLogicName = state.tValues;
      newPayload.selectedRows.judgeLogicCode = state.tValueCode;
      state.tableArr[state.newNo].maGpDetails[state.newButton].children.push(
        newPayload.selectedRows
      );
      state.tValue[state.newNo][state.newButton].push(newPayload.obj);

      return {
        ...state,
      };
    },
    deletePage(state, { payload }) {
      if (state.tableArr[state.newNo].maGpDetails) {
        state.tableArr[state.newNo].maGpDetails.forEach(item => {
          const newItem = item;
          state.requestData.forEach(c => {
            if (newItem.matId === c.matId) {
              delete newItem.judgeLogicName;
              delete newItem.judgeLogicCode;
            }
          });
          if (newItem.children) {
            newItem.children.forEach(d => {
              state.requestData.forEach(c => {
                if (c.matId === d.matId) {
                  delete newItem.judgeLogicName;
                  delete newItem.judgeLogicCode;
                }
              });
            });
            delete newItem.children;
          }
        });
      }
      const newTableArr = state.tableArr.filter(item => item.pageIdEdit !== payload.pageIdEdit);
      state.tValue.splice(payload.i, 1);
      state.headertitle.splice(payload.i, 1);
      return {
        ...state,
        tableArr: newTableArr,
      };
    },
    deletePageDom(state, { payload }) {
      const newRecord = payload.record;
      if (state.tableArr[state.newNo].maGpDetails[payload.i].children) {
        state.tableArr[state.newNo].maGpDetails[payload.i].children.forEach(c => {
          state.requestData.forEach(item => {
            const newItem = item;
            if (c.matId === item.matId) {
              delete newItem.judgeLogicName;
              delete newItem.judgeLogicCode;
            }
          });
        });
        delete newRecord.children;
      }
      const newTableArr = state.tableArr[state.newNo].maGpDetails.filter(
        item => item.matId !== payload.record.matId
      );
      state.tableArr[state.newNo].maGpDetails = newTableArr;
      return {
        ...state,
        ...payload,
      };
    },
    deletePageChildDom(state, { payload }) {
      state.tableArr[state.newNo].maGpDetails.forEach(c => {
        const newC = c;
        if (newC.children) {
          newC.children.forEach(k => {
            if (k.matId === payload.record.matId) {
              state.requestData.forEach(item => {
                const newItem = item;
                if (payload.record.matId === newItem.matId) {
                  delete newItem.judgeLogicName;
                  delete newItem.judgeLogicCode;
                  let a;
                  state.tValue[state.newNo].forEach((itemV, y) => {
                    const newItemV = itemV;
                    if (newItemV) {
                      a = newItemV.filter(newItems => newItems.matId !== payload.record.matId);
                    }
                    state.tValue[state.newNo][y] = a;
                  });
                }
              });
              const tableArrChild = newC.children.filter(
                item => item.matId !== payload.record.matId
              );
              newC.children = tableArrChild;
            }
          });
        }
      });
      return {
        ...state,
        ...payload,
      };
    },
    getMatDetail(state, { payload }) {
      // 近修改页面该地区是否合一
      const headertitle = [];
      const titleArr = [];
      const tValue = [];
      const newPayload = payload;
      Object.keys(payload).forEach(key => {
        if (key === 'contType' || key === 'contTypeName') {
          newPayload.serType = payload.contType.split(',');
        } else if (key === 'coltFlag') {
          newPayload[key] = payload[key].toString();
        } else if (key === 'areaId') {
          if (state.areaList.length) {
            const isShowId = state.areaList.some(item => item.areaId === payload[key]);
            if (!isShowId) {
              payload.areaIds = payload.areaIdName;
            } else {
              payload.areaIds = payload.areaId;
            }
          }
        }
        if (state.inputType && state.flagList) {
          if (key === 'maGpages') {
            payload[key].forEach((item, i) => {
              payload[key][i].maGpDetails = changeName(
                item.maGpDetails,
                state.inputType,
                state.flagList
              );
              tValue.push([]);
              payload[key][i].maGpDetails.forEach((page, index) => {
                page[`check+${page.matId}`] = page.reqFlag === 1;
                page[`dftVal+${page.matId}`] = page.dftVal;
                page[`pd+${page.matId}`] = page.pdId && page.pdId.split(',');
                tValue[i].push([]);
                if (page.children) {
                  page.children.forEach(padDetail => {
                    const obj = {};
                    obj.judgeLogicName = padDetail.judgeLogicName;
                    obj.judgeLogicCode = padDetail.judgeLogicCode;
                    obj.matId = padDetail.matId;
                    padDetail[`check+${padDetail.matId}`] = padDetail.reqFlag === 1;
                    padDetail[`dftVal+${padDetail.matId}`] = padDetail.dftVal;
                    padDetail[`pd+${padDetail.matId}`] =
                      padDetail.pdId && padDetail.pdId.split(',');
                    tValue[i][index].push(obj);
                  });
                }
                if (!page.children && Number(page.judgeFlag) === 1) {
                  page.children = [];
                }
              });
              headertitle.push(item.pageName);
              titleArr.push(true);
              item.pageIdEdit = item.pageId;
            });
          }
        }
      });
      return {
        ...state,
        ...payload,
        areaName: payload.areaIdName,
        headertitle,
        titleArr,
        tValue,
        tableArr: payload.maGpages,
      };
    },
    getAreaInsUnify(state, { payload }) {
      if (state.insUnifyFlag && Number(state.insUnifyFlag) !== Number(payload.insUnifyFlag)) {
        state.tableArr = [{ pageIdEdit: 0, maGpDetails: [] }];
        if (Number(payload.insUnifyFlag) === 1) {
          // 未加险种
          state.pdListData = JSON.parse(JSON.stringify(state.pdList));
        }
      }
      return {
        ...state,
        insUnifyFlag: payload.insUnifyFlag,
      };
    },
    getDictAss(state, { payload }) {
      const assArr = payload.BIZ_INS_TYPE;
      assArr.forEach(item => {
        state.pdListData.push(item);
      });
      return {
        ...state,
      };
    },
  },
};
